#!/usr/bin/env python
# -*- coding:utf8 -*-
"""
Author : mafei
Date   : 2019-12-22
"""
import re
from .base import ViewSecurityBase
from mmonitor.models.mysql_db import UserModel
from mmonitor.common.code_verify import captcha_verify
from mmonitor.utils.validator import is_uuid4
from mmonitor.common.vars import attack_msg, uri
from mmonitor.utils.send_mail import send_mail


class UserRegisterView(ViewSecurityBase):

    def get(self, request):
        user_id = request.qget_string("user_id")
        if not is_uuid4(user_id):
            return self.error_response(attack_msg)
        res = UserModel.get_or_none(UserModel.user_id == user_id)
        if res is None:
            return self.error_response(attack_msg)
        if not res.is_active:
            res.is_active = True
            res.save()
        return self.ok_response()

    def put(self, request):
        return self.ok_response()

    def post(self, request):
        """
            用户注册
            还需要做校验，发邮件激活

        """
        password = request.bget_string("password")
        email = request.bget_string("email")
        phone = request.bget_int("phone")
        verify = request.bget_dict("verify")

        email_match = r'^[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+){0,4}@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+){0,4}$'
        if not re.match(email_match, email):
            return self.logic_error_response("邮箱格式不正确")

        if captcha_verify(verify) != 0:
            return self.error_response("验证码错误，请重新刷新页面")

        res = UserModel.get_or_none(UserModel.email == email)
        if res:
            return self.error_response("用户名/邮箱已经存在了，麻烦重新换一个试试")
        d = {
            "password": password,
            "email": email,
            "phone": phone
        }
        res = UserModel.create(**d)
        print("发送的邮箱:{} user_id:{}".format(email, res.user_id))
        body = '监控网激活邮件，您在监控网有注册账号，可以点击 http://{}accout_activate.html?user_id={}  进行账号激活，如非自己操作的可以忽略'.format(uri,
            res.user_id)
        subject = '账号激活'
        send_mail(email, subject, body)

        return self.ok_response(msg="注册成功,请查收邮件进行账号激活")
